﻿using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using UnityEngine.Networking;
using LitJson;
using System;
using xuni;

namespace xres
{


    /// <summary>
    /// todo: 检查强更是一个流程, 下载强更又是一个流程
    /// </summary>
    public class ApkUpdateCheckAction : BaseAsyncAction
    {

        public const string Err_Notices_Network = "Err_Notices_Network";
        public const string Err_Notices = "Err_Notices";

        public const string Err_Down_File_Network = "Err_Down_File_Network";
        public const string Err_Down_File = "Err_Down_File";

        AsyncOperation _op;
        string _getUrl = "";

        public void Check()
        {
            if (BaseAsyncActionState.Init != _state)
                return;

            _state = "Check";

            //===== 生成url
            var reqParams = new List<KeyValuePair<string, string>>();
            reqParams.Add(new KeyValuePair<string, string>("version", "1.1.1"));
            reqParams.Add(new KeyValuePair<string, string>("type", "2"));
            reqParams.Add(new KeyValuePair<string, string>("sourceId", "10001"));

            var getUrl = HttpUtils.BuildGetUrl("http://192.168.1.213:8081/api_basketball/notices", reqParams);
            //=====

            var act = new GetJsonAction();
            act.onComplete.AddListener(OnComplete_GetNotices);
            act.GetJson(getUrl, true);
        }

        void OnComplete_GetNotices(object obj, string type, object data)
        {
            if (false) Debug.Log($"complete: Notices");

            var act = (GetJsonAction)obj;
            if (!string.IsNullOrEmpty(act.ErrType)) //请求强更公告出错
            {
                switch (act.ErrType)
                {
                case GetJsonAction.Err_Network:
                    SetError(Err_Notices_Network, act.ErrMsg);
                    break;

                default:
                    SetError(Err_Notices, act.ErrMsg);
                    break;
                }

                SetFinishAndNotify(ErrMsg);
                return;
            }

            var myVersion = new System.Version("1.0.1");

            var j_dataArr = new JsonData();
            {
                var j_data = new JsonData();
                j_dataArr.Add(j_data);
                j_data["version"] = "1.1.0";
                j_data["title"] = "测试标题";
                j_data["content"] = "测试内容,测试内容,测试内容,测试内容,测试内容";
                j_data["url"] = "http://localhost:8081/pcmaster_6.23_full_20200612.zip";
            }
            //var j_dataArr = action.data;
            for (var i = 0; i < j_dataArr.Count; ++i)
            {
                var j_data = j_dataArr[i];
                var serverVersion = new System.Version((string)j_data["version"]);
                if (myVersion >= serverVersion)
                    continue;

                //发现新版本, 弹框提示:
                var title = (string)j_data["title"];
                var content = (string)j_data["content"];
                var apkUrl = (string)j_data["url"];
                Debug.Log($"find force update, down: {apkUrl}");
                Download(apkUrl);
                return;
            }

            Debug.Log($"no force update, to res update"); //没有强更, 进入下一个流程

            SetError("", "");
            SetFinishAndNotify("");
        }

        void Download(string apkUrl)
        {
            var act = new DownloadFileAction();
            act.onComplete.AddListener(OnComplete_DownloadFile);
            act.Download(apkUrl, true, ResPath.BuildExternalPath("Apk/"), false, 0, 0);
        }

        void OnComplete_DownloadFile(object obj, string type, object data)
        {
            var act = (DownloadFileAction)obj;
            if (!string.IsNullOrEmpty(act.ErrType)) //下载出错
            {
                switch (act.ErrType)
                {
                case DownloadFileAction.Err_Network:
                case DownloadFileAction.Err_Download_File:
                case DownloadFileAction.Err_Crc32:
                    //todo: 重试多次还是失败, 则尝试删除再试或提示联系客服解决
                    SetError(Err_Down_File_Network, act.ErrMsg);
                    break;

                case DownloadFileAction.Err_Http:
                    SetError(Err_Down_File, act.ErrMsg);
                    break;
                }

                SetFinishAndNotify(ErrMsg);
                return;
            }

            //下载完成, 开始安装
            Debug.Log($"down finish: install apk");
#if UNITY_ANDROID
            JsonData jsData = new JsonData();
            jsData["path"] = action.filePath;
            //PluginsUtils.LuaCall("installAPK", JsonMapper.ToJson(jsData));
#elif UNITY_IPHONE || UNITY_IOS
            //总是通过appstore强更
#else
            //暂不支持
#endif
        }


    } //end of class


}
